<template>
  <div class="talk">
    <button @click="getLoveTalk">获取一句土味情话</button>
    <ul>
      <li v-for="item of talkList" :key="item.id">{{ item.title }}</li>
    </ul>
  </div>
</template>

<script setup lang="ts" name="LoveTalk">
import axios from "axios";
import { nanoid } from "nanoid";
import { reactive } from "vue";

// 数据
const talkList = reactive([
  {
    id: "tw001",
    title: "今天你有点怪，哪里怪？怪好看的！",
  },
]);

// 方法
async function getLoveTalk() {
  try {
    // 接收请求成功返回的数据并进行解构获取最终数据
    const {
      data: { content: title }, // 多层解构并将content进行重命名
    } = await axios.get("https://api.uomg.com/api/rand.qinghua?format=json");
    // 将请求成功的数据包装成一个对象
    const talk = {
      id: nanoid(), // 使用nanoid用于生成唯一id
      title,
    };
    // 将数据添加到数组中
    talkList.unshift(talk);
  } catch (error) {
    console.warn(error);
  }
}
</script>

<style scoped>
.talk {
  background-color: orange;
  padding: 10px;
  border-radius: 10px;
  box-shadow: 0 0 10px;
}
</style>
